package com.atm.thirdplt.service.impl;

import com.atm.thirdplt.common.constant.MongoCollConstants;
import com.atm.thirdplt.common.core.domain.lis.LisLabResult;
import com.atm.thirdplt.common.core.domain.lis.LisLabTestMaster;
import com.atm.thirdplt.common.utils.DateUtils;
import com.atm.thirdplt.common.utils.StringUtils;
import com.atm.thirdplt.dao.mapper.lis.LisInfMapper;
import com.atm.thirdplt.dao.mapper.sys.LocalInfMapper;
import com.atm.thirdplt.service.ILisInfService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * lis数据同步业务实现类
 *
 * @author atm
 */
@Service
public class LisInfServiceImpl implements ILisInfService {
    private static final Logger log = LoggerFactory.getLogger(LisInfServiceImpl.class);

    @Autowired
    private LisInfMapper lisInfMapper;

    @Autowired
    private LocalInfMapper localInfMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    @Qualifier("primaryJdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    @Override
    public void delLabMasterMongo(String patId, String visitId) {
        Criteria cria = Criteria.where("patientId").is(patId);

        if (StringUtils.isNotEmpty(visitId)) {
            cria.and("visitId").is(visitId);
        }
        Query query = Query.query(cria);
        mongoTemplate.remove(query, LisLabTestMaster.class, MongoCollConstants.LIS_LAB_TEST_MASTER);
    }

    @Override
    public void saveLabMasterMongo(List<LisLabTestMaster> labMaster) {
        mongoTemplate.insert(labMaster, MongoCollConstants.LIS_LAB_TEST_MASTER);
    }

    @Override
    public void delLabMaster(String patId, String visitId) {
        localInfMapper.delLabMaster(patId, visitId);
    }

    @Override
    public void saveLabMaster(List<LisLabTestMaster> list) {
        long start = System.currentTimeMillis();

        jdbcTemplate.batchUpdate("insert into atm_lab_test_master(test_no, priority_indicator, patient_id, visit_id, " +
                "name, " +
                "working_id, test_cause, relevant_clinic_diag, specimen, spcm_received_date_time,\n" +
                "        ordering_dept, ordering_provider, PERFORATM_BY, result_status,RESULTS_RPT_DATE_TIME, " +
                "transcriptionist, verified_by)" +
                "  values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", new BatchPreparedStatementSetter() {

            @Override
            public int getBatchSize() {
                return list.size();
            }

            @Override
            public void setValues(PreparedStatement ps, int i)
                    throws SQLException {
                ps.setString(1, list.get(i).getTestNo());
                ps.setInt(2, list.get(i).getPriorityIndicator());
                ps.setString(3, list.get(i).getPatientId());
                ps.setString(4, list.get(i).getVisitId());
                ps.setString(5, list.get(i).getName());
                ps.setString(6, list.get(i).getWorkingId());
                ps.setString(7, list.get(i).getTestCause());
                ps.setString(8, list.get(i).getRelevantClinicDiag());
                ps.setString(9, list.get(i).getSpecimen());
                if (list.get(i).getSpcmReceivedDateTime() != null) {
                    ps.setDate(10, new Date(list.get(i).getSpcmReceivedDateTime().getTime()));
                } else {
                    ps.setDate(10, null);
                }

                ps.setString(11, list.get(i).getOrderingDept());
                ps.setString(12, list.get(i).getOrderingProvider());
                ps.setString(13, list.get(i).getPerformedBy());
                ps.setString(14, list.get(i).getResultStatus());
                if (list.get(i).getResultsRptDateTime() != null) {
                    ps.setDate(15, new Date(list.get(i).getResultsRptDateTime().getTime()));
                } else {
                    ps.setDate(15, null);
                }

                ps.setString(16, list.get(i).getTranscriptionist());
                ps.setString(17, list.get(i).getVerifiedBy());
            }
        });

        long end = System.currentTimeMillis();
        log.info("时间差：" + (end - start));
    }


    @Override
    public void delLabResultMongo(List<String> testNoList) {
        Query query = Query.query(Criteria.where("testNo").in(testNoList));
        mongoTemplate.remove(query, LisLabResult.class, MongoCollConstants.LIS_LAB_RESULT);
    }

    @Override
    public void saveLabResultMongo(List<LisLabResult> labResult) {
        mongoTemplate.insert(labResult, MongoCollConstants.LIS_LAB_RESULT);
    }

    @Override
    public void delLabResult(List<String> labResult) {
        localInfMapper.delLabResult(labResult);
    }

    @Override
    public void saveLabResult(List<LisLabResult> list) {
        long start = System.currentTimeMillis();

        jdbcTemplate.batchUpdate("insert into atm_lab_result(test_no, report_item_name, report_item_code, " +
                "abnormal_indicator, result, units, result_date_time, reference_result)" +
                "  values(?,?,?,?,?,?,?,?)", new BatchPreparedStatementSetter() {

            @Override
            public int getBatchSize() {
                return list.size();
            }

            @Override
            public void setValues(PreparedStatement ps, int i)
                    throws SQLException {
                ps.setString(1, list.get(i).getTestNo());
                ps.setString(2, list.get(i).getReportItemName());
                ps.setString(3, list.get(i).getReportItemCode());
                ps.setString(4, list.get(i).getAbnormalIndicator());
                ps.setString(5, list.get(i).getResult());
                ps.setString(6, list.get(i).getUnits());
                if (list.get(i).getResultDateTime() != null) {
                    ps.setDate(7, new Date(list.get(i).getResultDateTime().getTime()));
                } else {
                    ps.setDate(7, null);
                }

                ps.setString(8, list.get(i).getReferenceResult());
            }
        });

        long end = System.currentTimeMillis();
        log.info("时间差：" + (end - start));
    }
}
